package com.fengke.util.page;

public class OracleDialect implements Dialect {

	protected static final String SQL_END_DELIMITER = ";";

	public String getLimitString(String sql, boolean hasOffset) {
		return sql;
	}

	public String getLimitString(String sql, int offset, int limit) {
		sql = trim(sql);
		StringBuffer sb = new StringBuffer(sql.length() + 100);
		sb.append(sql);
		//        int from = sb.indexOf(" FROM ");
		//        if(from == -1)
		//        	from  = sb.indexOf(" from ");
		//        int where = sb.indexOf(" WHERE ");
		//        if(where == -1)
		//        	where = sb.indexOf(" where ");
		//        int orderby = sb.indexOf(" ORDER BY ");
		//        if(orderby == -1)
		//        	orderby = sb.indexOf(" order by ");
		//        int groupby = sb.indexOf(" GROUP BY ");
		//        if(groupby == -1)
		//        	groupby = sb.indexOf(" group by ");
		//        int having = sb.indexOf(" HAVING ");
		//        if(having == -1)
		//        	having = sb.indexOf(" having ");
		//        String orderbySubSql = "";
		//        if(orderby != -1) {
		//	        orderbySubSql = sb.substring(orderby);
		//	        sb.delete(orderby, sb.length());
		//        }
		//        int pos = findPosition(groupby, having);
		//    	if(pos != -1) {
		//	        if(where != -1) {
		//	        	sb.insert(pos, " AND rownum <= " + (offset + limit));
		//	        }
		//	        else
		//	        	sb.insert(pos, " WHERE rownum <= " + (offset + limit));
		//    	}
		//    	else {
		//	        if(where != -1) {
		//	        	sb.append(" AND rownum <= " + (offset + limit));
		//	        }
		//	        else
		//	        	sb.append(" WHERE rownum <= " + (offset + limit));
		//    	}
		//        sb.insert(from, " ,rownum rn");
		//		sb.insert(0, "SELECT * FROM (");
		//		sb.append(")");
		//		sb.append(" WHERE rn > ").append(offset);
		//		if(orderby != -1) {
		//			sb.append(orderbySubSql);
		//		}
		sb.insert(0, "SELECT * FROM (SELECT rownum rn, tt.* FROM (");
		sb.append(") tt WHERE rownum <= " + (offset + limit));
		sb.append(") WHERE rn > ").append(offset);
		return sb.toString();
	}

	public boolean supportsLimit() {
		return true;
	}

	//	private int findPosition(int groupby, int having) {
	//		if(groupby == -1 && having == -1)
	//			return -1;
	//		if(groupby == -1)
	//			groupby = 1048576;
	//		if(having == -1)
	//			having = 1048576;
	//		return Math.min(groupby, having);
	//	}

	private String trim(String sql) {
		sql = sql.trim();
		if (sql.endsWith(SQL_END_DELIMITER)) {
			sql = sql.substring(0, sql.length() - 1 - SQL_END_DELIMITER.length());
		}
		return sql;
	}
}
